package com.ldw.chapter5.config;

import com.ldw.chapter5.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注销登录
 * <p>Title: WebSecurityConfig</p>
 * <p>Description: </p>
 *
 * @author: dwLiu
 * @date: 2020/3/21 20:50
 */
@EnableWebSecurity
public class WebSecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .logout()
                //指定接受注销请求的路由
                .logoutUrl("/myLogout")
                //注销成功，重定向到该路径下
                .logoutSuccessUrl("/")
                //注销成功的处理方式，不同于logoutSuccessUrl的重定向，logoutSuccessHandler更加灵活
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

                    }
                })
                //使该用户的HttpSession失效
                .invalidateHttpSession(true)
                //注销成功，删除指定的cookie
                .deleteCookies("cookie1","cookie2")
                //用于注销的处理句柄，允许自定义一些清理策略,事实上LogoutSuccessHandler也能做到
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

                    }
                });
    }
}
